import {Component, OnInit, ViewChild} from '@angular/core';
import {ProductService} from '../product.service';
import {ProductlistService} from '../list/productlist.service';
import {adSystemApiUrl, AliyunOssOutputUrl, appletApiUrl} from '../../../../config/api';
import {Router, ActivatedRoute, ParamMap} from '@angular/router';
import {NzModalService, NzMessageService} from 'ng-zorro-antd';
import {EditorComponent} from '../../../comm-components/wangeditor/editor.component';
import {AdOssUploadService} from '../../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {productaddService} from './productadd.service';

import 'rxjs/add/operator/switchMap';

import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import {first} from 'rxjs/operator/first';
import {HttpService} from '../../../lib/service/http.service';
import {TemplateService} from '../../template/template.service';

@Component({
  selector: 'product-add',
  templateUrl: './productadd.component.html',
  styleUrls: ['./productadd.component.scss'],
  providers: [ProductService, ProductlistService, AdOssUploadService, LocalStorageService, productaddService, TemplateService]
})


export class ProductaddComponent implements OnInit {
  validateForm: FormGroup;
  _isSpinning = false;
  groupList = [];
  ghostList = [];
  deleteList = [];
  typeValue = '';
  addshow = false;
  specValue = 1; // 规格
  specIndex = 1;
  specList = [];
  specList1 = [];
  readonly = false;
  editStatus = false;
  @ViewChild(EditorComponent) editor: EditorComponent;
  shopid: any;
  templateList: any;
  categories = null;

  constructor(private ProductService: ProductService,
              private ProductlistService: ProductlistService,
              private productaddService: productaddService,
              private _message: NzMessageService,
              private route: ActivatedRoute, private fb: FormBuilder,
              private localStorageService: LocalStorageService,
              private router: Router,
              private adOssUploadService: AdOssUploadService,
              private templateService: TemplateService,
  ) {

  }

  description = '';
  place = [];
  grouplist1 = [];
  picList = [];
  imgs = [];
  fileList = [];
  placeError = false;
  flag = true;
  // 文件名
  f1 = ['first_picture', 'second_picture', 'third_picture', 'fourth_picture'];
  selectedOption = null;

  goProductList() {
    // if(this.flag) {
    this.router.navigate(['member/product/list']);
    // this.flag = false;
    // }
  }

  uploadImg(product_id) {
    const member_id = this.localStorageService.getUserInfo().id;
    const applet_id = this.localStorageService.getNowApplet().id;
    this.adOssUploadService
      .getSignature(`/v1/member/detail/${member_id}/${applet_id}/${product_id}?callback=true`)
      // .getSignature1(`/v1/common/upload`,'/v1/member/goods/edit')
      .subscribe(
        res1 => {
          console.log(res1);
          const length = this.fileList.filter(item => {
            return item && item != 'pic';
          }).length;
          let successLen = 0;
          if (length == 0) {
            this.addStatus = true;
            this._message.create('success', '添加成功');
            this.router.navigate(['member/product/list/all']);
            return false;
          }
          this.fileList.every((val, idx, array) => {
            if (val && val != 'pic') {
              this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + val.name.replace(/.+\./, '').toLowerCase(), this.f1[idx])
              // this.adOssUploadService.fileUpload(val, res1.data, '/' + new Date().getTime() + '.' + val.name.replace(/.+\./, '').toLowerCase(), this.f1[idx])
                .subscribe(res2 => {
                    successLen++;
                    if (successLen == length) {
                      this.addStatus = true;
                      this._message.create('success', '添加成功');
                      this.router.navigate(['member/product/list/all']);
                    }
                  }
                );
            }
            return true;
          });

        }
      );
  }

  addStatus = true;
  picError = false; //图片是否错误
  fileChange(list) {
    console.log('list----', list);
    console.log('files=', this.fileList);
    if (this.fileList.length === 0 && this.picList.length === 0) {
      this.picError = true;
    }
    else {
      const length = this.fileList.filter(item => {
        return item && item !== 'pic';
      }).length;
      if (length === 0) {
        // this.submitStatus = false;
        return false;
      }
      // @ts-ignore
      this.fileList.every((val, index) => {
        console.log('val-', typeof val);
        if (val !== 'pic') {
          this.adOssUploadService.fileUpload_(val, '商品添加').subscribe(res => {
              this.picError = false;
              this.imgs[index] = res.data.filename_save;
              console.log('pic', this.imgs);
              this.fileList[index] = 'pic';
              this._message.create('success', '添加成功');
            }
          );
        }
        return true;
      });
    }
  }

  picChange(where) {
    console.log('where', where);
    if (where !== 'undefined') {
      this.imgs.splice(where - 1, 1);
      console.log('imgs', this.imgs);
      if (this.deleteList.length === 0) {
        this.deleteList.push(where);
      } else {
        this.deleteList.map((e, i) => {
          if (e !== where) {
            this.deleteList.push(where);
          }
        });
      }
    }
  }

  deletePic(where) {
    const member_id = this.localStorageService.getUserInfo().id;
    const applet_id = this.localStorageService.getNowApplet().id;
    const url = `${adSystemApiUrl}/v1/member/detail/${member_id}/${applet_id}/${this.productId}/del/${where}`;
    this.productaddService.deletePic(url).subscribe(res => {
      console.log(res);
    });
  }

  cityvalueChange(data) {
    if (data.length > 0) {
      this.placeError = false;
    }
  }

  checkspecValue() {
    const validateForm = this.validateForm;
    let pd = false;
    const idsArr = this.idsArr;
    const specArr = this.specArr;
    for (let i = 0, len = specArr.length; i < len; i++) {
      if ((validateForm.controls['[' + idsArr[i] + '][price_discount]'].dirty &&
        validateForm.controls['[' + idsArr[i] + '][price_discount]'].hasError('required')) ||
        (validateForm.controls['[' + idsArr[i] + '][price_origin]'].dirty &&
          validateForm.controls['[' + idsArr[i] + '][price_origin]'].hasError('required')) ||
        (validateForm.controls['[' + idsArr[i] + '][in_stock]'].dirty &&
          validateForm.controls['[' + idsArr[i] + '][in_stock]'].hasError('required'))
      ) {
        pd = true;
        break;
      }
    }
    return pd;
  }

  inputchange(e, control, type = 'money') {
    let data = e.target.value;
    const json = {};
    let reg = null;
    if (type == 'money') {
      reg = data.match(/\d+\.?\d{0,2}/);
    } else if (type == 'number') {
      reg = data.match(/\d+/);
    }
    if (reg != null) {
      data = reg[0];
    } else {
      data = '';
    }
    json[control] = data;
    this.validateForm.patchValue(json);
  }

  update_norm_mode = 0;
  specError = false;
  oldSpecObj = {};

  _submitForm() {
    console.log('proid', this.productId);
    const validateForm = this.validateForm;
    const idsArr = this.idsArr;
    const sku = this.sku;
    const specArr = [];
    // for (const i in this.validateForm.controls) {
    //   if (i == 'price') {
    //     this.validateForm.get('price.price').markAsDirty();
    //     this.validateForm.get('price.price1').markAsDirty();
    //   }
    //   this.validateForm.controls[i].markAsDirty();
    // }
    let otherpd = true;

    if (this.fileList.length == 0 || this.picList.length == 0) {
      otherpd = false;
      this.picError = true;
    } else {
      this.picError = false;
    }
    if (validateForm.controls.spec.value == 2 && this.specArr.length == 0) {
      otherpd = false;
      this.specError = true;
    } else {
      this.specError = false;
    }

    this.description = this.editor.clickHandle();

    if (this.picList[0]['src'] === '') {
      this._message.create('error', '第一张主图不能为空');
      return;
    }

    // return false;
    if (this.validateForm.valid && otherpd) {
      this.addStatus = false;
      if (this.deleteList.length > 0) {
        this.deleteList.map((e, i) => {
          this.deletePic(e);
        });
      }
      if (this.productId) {
        let specArr = [];
        if (validateForm.controls.spec.value == 2) {//多规格
          const idsArr = this.idsArr;
          const valueArr = this.valueArr;
          specArr = this.specArr.map((item, index) => {
            this.skus[sku[index].join('_')]['price_origin'] = validateForm.controls['[' + idsArr[index] + '][price_origin]'].value;
            this.skus[sku[index].join('_')]['price_discount'] = validateForm.controls['[' + idsArr[index] + '][price_discount]'].value;
            this.skus[sku[index].join('_')]['in_stock'] = validateForm.controls['[' + idsArr[index] + '][in_stock]'].value;
            const json = {
              attributes: sku[index].join('_'),
              'price_origin': validateForm.controls['[' + idsArr[index] + '][price_origin]'].value,
              'price_discount': validateForm.controls['[' + idsArr[index] + '][price_discount]'].value,
              'in_stock': validateForm.controls['[' + idsArr[index] + '][in_stock]'].value,
              'id': validateForm.controls['[' + idsArr[index] + '][isbn]'].value,
            };
            return json;
          });
        }
        ;
        const categories = [];
        let _categories = validateForm.controls.categories.value;
        if (_categories[0].id) {
          categories.push(_categories[0].id);
        } else {
          const _index = _categories.length - 1;
          if (_index >= 0) {
            categories.push(_categories[_index]);
          }
          ;
        }

        this.ProductService.editGood(
          this.productId,
          this.shopid,
          categories,
          validateForm.controls.name.value, // 商品名称
          validateForm.controls.numbers.value, // 产品编码
          validateForm.controls.price_discount.value, //小程序售价
          validateForm.controls.price_origin.value, //原价
          validateForm.controls.for_sale.value, //上下架
          this.imgs,
          this.description, //描述
          validateForm.controls.is_recommend.value, // 是否热销
          validateForm.controls.for_sale.value,
          validateForm.controls.spec.value === 1 ? 0 : validateForm.controls.template.value,
          specArr
        ).subscribe(res => {
          this.addStatus = true;
          if (res.code === 200) {
            this._message.create('success', '修改成功');
            this.router.navigate(['member/product/list/all']);
          } else {
            // this.addStatus = true;
            this._message.create('error', res.message);
          }
        });
      }
      else {
        let specArr = [];
        if (validateForm.controls.spec.value == 2) {//多规格
          const idsArr = this.idsArr;
          const sku = this.sku;
          console.log('sku', sku);
          specArr = this.specArr.map((item, index) => {
            this.skus[sku[index].join('_')]['price_origin'] = validateForm.controls['[' + idsArr[index] + '][price_origin]'].value;
            this.skus[sku[index].join('_')]['price_discount'] = validateForm.controls['[' + idsArr[index] + '][price_discount]'].value;
            this.skus[sku[index].join('_')]['in_stock'] = validateForm.controls['[' + idsArr[index] + '][in_stock]'].value;
            const json = {
              attributes: sku[index].join('_'),
              'price_origin': validateForm.controls['[' + idsArr[index] + '][price_origin]'].value,
              'price_discount': validateForm.controls['[' + idsArr[index] + '][price_discount]'].value,
              'in_stock': validateForm.controls['[' + idsArr[index] + '][in_stock]'].value,
              'id': validateForm.controls['[' + idsArr[index] + '][isbn]'].value,
            };
            return json;
          });
        }
        console.log('skus', this.skus);
        console.log('specArr', this.specArr);
        const categories = [];
        let _categories = validateForm.controls.categories.value;
        let _index = _categories.length - 1;
        if (_index >= 0) {
          categories.push(_categories[_index]);
        }
        ;
        this.ProductService.addGoods(
          this.shopid,
          categories,
          validateForm.controls.name.value, // 商品名称
          validateForm.controls.numbers.value, // 产品编码
          validateForm.controls.price_discount.value, //小程序售价
          validateForm.controls.price_origin.value, //原价
          validateForm.controls.for_sale.value, //上下架
          this.imgs,
          this.description, //描述
          validateForm.controls.is_recommend.value, // 是否热销
          validateForm.controls.for_sale.value,
          validateForm.controls.spec.value === 1 ? 0 : validateForm.controls.template.value,
          specArr
        ).subscribe(res => {
          this.addStatus = true;
          if (res.code === 200) {
            this._message.create('success', '添加成功');
            this.router.navigate(['member/product/list/all']);
          } else {
            // this.addStatus = true;
            this._message.create('error', res.message);
          }
        });
      }

    } else {
      this._message.create('error', '请补充商品必填信息');
    }

  }

  // wangEdit编辑器
  PostData(event): void {
    // console.log(event);
  }

  prevent(event) {
    event.preventDefault();
  }

  freshTemplate(event) {
    event.preventDefault();
    this.gettemplateList();
  }

  options = [];
  dataSave: any = {};

  ngOnInit() {
    // this.editor.changedEitorUsePlace('goods');
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]], // 名字
      numbers: [null], // 编码
      spec: [1],
      price_discount: [null, [Validators.required, Validators.pattern('^[0-9]+([\.][0-9]{1,2})?$')]], //折扣价
      price_origin: [null, [Validators.required, Validators.pattern('^[0-9]+([\.][0-9]{1,2})?$')]], //原价
      template: [null],
      categories: [null, [Validators.required]],
      is_recommend: [0],
      for_sale: [0],
    });

    this.validateForm.get('name').valueChanges.subscribe(data => {
      if (data.length > 40) {
        this.validateForm.patchValue({
          name: data.substring(0, 40)
        });
      }
    });

    this.route.params.subscribe((params) => {
      this.shopid = this.localStorageService.getShop()['id'];
      this.getTempList();
      this.getGroupList();
      if (params.id) {
        this.productId = params.id;
        console.log('this.productId', this.productId);
        this.getDetail(params.id);
        this.getGroupList(params.id);
      }
      else {
        const len = 4;
        for (let i = 0; i < len; i++) {
          this.picList.push({'src': ''});
          this.fileList.push('pic');
        }
      }
    });

    this.validateForm.get('template').valueChanges.subscribe(res => {
      console.log('res', res);
      this.templateList.forEach(item => {
        if (item.id === res) {
          this.specList = item.attributes;
          // this.initspecList();
          this.setspecArr();
        }
        ;
      });
    });
  }

  valueArr = [];

  initspecList() {
    console.log('speclist', this.specList);
    this.specList.forEach((item) => {
      this.validateForm.addControl('spec[' + item.index + ']', this.fb.control(item.title));

      item.attribute_values.forEach((item1) => {
        this.validateForm.addControl('spec[' + item.index + '][' + item1.index + ']', this.fb.control(item1.title));
      });
    });
  }

  productId = 0;
  norm_mode1 = 1;

  getDetail(id) {
    this.ProductlistService.getGoodsInfoById(this.shopid, id).subscribe(res => {
      if (res.code === 200) {
        const data = res.data;
        const validateForm = this.validateForm;
        this.norm_mode1 = data.attribute_template_id === 0 ? 1 : 2,
          this.description = data.content;
        validateForm.patchValue({
          name: data.name,
          spec: data.attribute_template_id === 0 ? 1 : 2,
          categories: data.categories,
          numbers: data.numbers,
          is_recommend: data.is_recommend,
          for_sale: data.for_sale,
          price_discount: data.price_discount,
          price_origin: data.price_origin,
          template: data.attribute_template_id
        });

        if (data.attribute_template_id !== 0) {
          data.skus.forEach(item => {
            this.valueArr.push({
              attribute_values: item.attribute_values,
              id: item.id,
              price_discount: item.price_discount ,
              price_origin: item.price_origin,
              in_stock: item.in_stock,
              isbn: item.id,
            });
          });
          this.setspecArr();
        }

        this.editor.loadingHandle(this.description);
        this.imgs = data.pics;
        this.f1.forEach((item, i) => {
          this.fileList.push('pic');
          if (data.pics[i]) {
            this.picList.push({
              src: appletApiUrl + '/common/attachment/view/' + data.pics[i] + '?' + Date.now(),
              where: i + 1
            });
            this.ghostList.push({where: i + 1});
            this.editStatus = true;
          } else {
            this.picList.push({src: '', where: i + 1});
          }
        });
      }
    });
  }

  getCustomSkuByGoodsId(id) {
    this.ProductService.getCustomSkuByGoodsId(id).subscribe(res => {
      if (res.code === 2000) {
        const arr1 = [];
        const arr3 = [];
        const arr2 = [];
        const loadedArr = this.loadedArr;
        res.data.forEach(item => {
          const index = arr1.indexOf(item.custom_goods_attribute_id);
          item.value = item.custom_goods_attribute_value_name;
          item.bind = true;
          item.id = item.custom_goods_attribute_value_id;
          item.goods_attribute_name = item.custom_goods_attribute_value_name;
          item.goods_attribute_set_remark = item.custom_goods_attribute_value_name;
          item.is_private = true;
          item.goods_attribute_set_id = item.custom_goods_attribute_id;
          item.goods_attribute_id = item.custom_goods_attribute_id;
          if (index < 0) {
            arr1.push(item.custom_goods_attribute_id);
            arr3.push(item.custom_goods_attribute_value_id);
            arr2.push({
              attribute_id1: 1,
              attribute_id: item.custom_goods_attribute_id,
              titleAdd: true,
              title: item.custom_goods_attribute_name,
              index: arr1.length,
              childLen: 1,
              list: [
                {
                  title: item.custom_goods_attribute_value_name,
                  index: 0,
                  attribute_value_id: item.custom_goods_attribute_value_id,
                  attribute_value_id1: 1
                }
              ]
            });
            this.specIndex++;
            loadedArr[arr1.length] = {index, name: item.custom_goods_attribute_name, list: [item]};

          } else if (arr3.indexOf(item.custom_goods_attribute_value_id) < 0) {
            arr3.push(item.custom_goods_attribute_value_id);
            arr2[index].list.push({
              title: item.custom_goods_attribute_value_name,
              index: arr2[index].childLen,
              attribute_value_id: item.custom_goods_attribute_value_id,
              attribute_value_id1: 1
            });
            loadedArr[arr2[index].index].list.push(item);
            arr2[index].childLen++;
          }
        });
        let arr2Again = false;
        if (arr2.length > 0) {
          this.specList = arr2;
          this.initspecList();
        } else {
          arr2Again = true;
        }
        this.ProductService.getGoodsSkubindList(id).subscribe(res => {
          if (res.code == 2000) {
            const itemObj = {};
            res.data.forEach(item => {
              const sku_info = JSON.parse(item.sku_info);

              //sku列表循环
              if (arr2Again) {
                const sku2 = sku_info.sku.length > 0 ? sku_info.sku : sku_info.sku2;
                sku2.forEach(item1 => {
                  const index = arr1.indexOf(item1.goods_attribute_id);
                  item1.value = item1.goods_sku_attribute_value_name;
                  item1.bind = true;
                  item1.id = item1.goods_attribute_value_id;
                  item1.goods_attribute_name = item1.goods_sku_attribute_value_name;
                  item1.goods_attribute_set_remark = item1.goods_sku_attribute_value_name;
                  item1.is_private = true;
                  item1.goods_attribute_set_id = item1.goods_attribute_id;
                  item1.goods_attribute_id = item1.goods_attribute_id;

                  if (index < 0) {
                    arr1.push(item1.goods_attribute_id);
                    arr3.push(item1.goods_attribute_value_id);
                    arr2.push({
                      attribute_id1: 1,
                      attribute_id: item1.goods_attribute_id,
                      titleAdd: true,
                      title: item1.goods_sku_attribute_name,
                      index: arr1.length,
                      childLen: 1,
                      list: [
                        {
                          title: item1.goods_sku_attribute_value_name,
                          index: 0,
                          attribute_value_id: item1.goods_attribute_value_id,
                          attribute_value_id1: 1
                        }
                      ]
                    });
                    this.specIndex++;
                    loadedArr[arr1.length] = {index, name: item1.goods_sku_attribute_name, list: [item1]};

                  } else if (arr3.indexOf(item1.goods_attribute_value_id) < 0) {
                    arr3.push(item1.goods_attribute_value_id);
                    arr2[index].list.push({
                      title: item1.goods_sku_attribute_value_name,
                      index: arr2[index].childLen,
                      attribute_value_id: item1.goods_attribute_value_id,
                      attribute_value_id1: 1
                    });
                    loadedArr[arr2[index].index].list.push(item1);
                    arr2[index].childLen++;
                  }

                  if (!itemObj[item1.goods_attribute_value_id]) {
                    itemObj[item1.goods_attribute_value_id] = item1;
                  }
                });
              } else {
                const sku2 = sku_info.sku2.length > 0 ? sku_info.sku2 : sku_info.sku;
                sku2.forEach(item2 => {
                  console.log('item2:', item2);
                  if (!itemObj[item2.goods_attribute_value_id]) {
                    itemObj[item2.goods_attribute_value_id] = item2;
                  }
                });
              }

              this.valueArr.push({
                id: item.id,
                price_discount: item.price_discount,
                price_origin: item.price_origin,
                in_stock: item.in_stock,
                isbn: item.id,
                sku_info: sku_info
              });
            });
            if (arr2Again) {
              this.specList = arr2;
              this.initspecList();
            }

            const oldSpecObj = {};
            arr2.forEach(item => {
              item.list.forEach(item1 => {
                oldSpecObj[item1.attribute_value_id] = itemObj[item1.attribute_value_id];
              });
            });
            this.oldSpecObj = oldSpecObj;
            this.setspecArr();
          }
        });
        //this.setspecArr();

      }
    });
  }

  gettemplateList(callback = null) {
    this.ProductService.getExpressTemplateList().subscribe(res => {
      if (res.code == 2000) {
        if (res.data.data.length > 0) {
          this.options = res.data.data.map(item => {
            return {
              label: item.name,
              value: item.id
            };
          });
          if (typeof callback == 'function') {
            callback();
          }
        }
      }
    });
  }

  specListObj = {};
  loadedArr = {};

  setEdit(e, item) {
    e.preventDefault();
    item.edit = true;
  }

  bindGoodsCategory(e, item, index) {
    e.preventDefault();
    if (item.loading) {
      return false;
    }
    const validateForm = this.validateForm;
    const name = validateForm.controls['spec[' + item.index + ']'].value;
    let arr = [];
    const delArr = [];
    const valuedArr = [];
    if (!name) {
      this._message.create('error', '请配置规格名');
      return false;
    }
    if (item.attribute_id1 && this.delObj[item.attribute_id]) {
      console.log('nnneeeggg');
      this.update_norm_mode = 1;
    }
    const list = item.list.filter(item1 => {
      const value = validateForm.controls['spec[' + item.index + '][' + item1.index + ']'].value;
      if (valuedArr.indexOf(value) >= 0) {
        validateForm.removeControl('spec[' + item.index + '][' + item1.index + ']');
        return false;
      } else if (value) {
        valuedArr.push(value);
        return true;
      } else {
        validateForm.removeControl('spec[' + item.index + '][' + item1.index + ']');
        return false;
      }
    });
    if (list.length == 0) {
      this._message.create('error', '请配置规格值');
      return false;
    }
    item.list = list;
    arr = item.list.map(item1 => {
      return validateForm.controls['spec[' + item.index + '][' + item1.index + ']'].value;
    });
    item.loading = true;
    this.ProductService.bindGoodsCategory(70, name, arr).subscribe(res => {
      if (res.code == 2000) {
        res.data.custom_goods_attribute_value.forEach(item1 => {
          item1.goods_attribute_name = res.data.name;
          item1.goods_attribute_set_remark = res.data.name;
          item1.bind = true;
          item1.is_private = true;
          item1.goods_attribute_set_id = item1.custom_goods_attribute_id;
          item1.goods_attribute_id = item1.custom_goods_attribute_id;
        });
        const loadedArr = this.loadedArr;
        const nameArr = arr;
        const listArr = nameArr.map(item => {
          return null;
        });
        res.data.custom_goods_attribute_value.forEach(item => {
          const index = nameArr.indexOf(item.value);
          listArr[index] = item;
        });

        if (loadedArr[item.index]) {
          loadedArr[item.index] = {index, name: res.data.name, list: listArr};
        } else {
          loadedArr[item.index] = {index, name: res.data.name, list: listArr};
        }
        this.setspecArr(); //得到 规格table list
        item.titleAdd = true;
        item.edit = false;
        item.loading = false;
        this.specError = false;
        this._message.create('success', '规格创建成功，请配置规格小程序售价、原价、库存等具体值');
      }
    });
  }

  specArr = [];
  specArr1 = [];
  idsArr = [];
  sku = [];
  skus = [];

  setspecArr() {
    const arr = [];
    this.specList.forEach(item => {
      arr.push(item.attribute_values);
    });
    const skus = [];
    console.log('arr', arr);
    const returnArr = [];
    this.getarrAll(arr, returnArr, 0, []);
    this.getskuAll(arr, this.sku, 0, []);
    console.log('skus', this.skus);
    this.sku.forEach(item => {
      console.log(item.join(','));
      // this.skus.push(item.join(','));
      this.skus[item.join('_')] = [];
    });
    console.log('skus', this.skus);

    const validateForm = this.validateForm;
    if (this.specArr.length > 0) { //解除数据绑定
      this.specArr.forEach(item => {
        const ids = [];
        item.forEach(item1 => {
          ids.push(item1.id);
        });
        validateForm.removeControl('[' + ids.join(',') + '][price_discount]');
        validateForm.removeControl('[' + ids.join(',') + '][price_origin]');
        validateForm.removeControl('[' + ids.join(',') + '][in_stock]');
        validateForm.removeControl('[' + ids.join(',') + '][isbn]');
      });
    }
    this.specArr = returnArr;
    console.log('specArr', this.specArr);
    this.idsArr = [];
    const valueArr = this.valueArr;
    this.specArr.forEach((item, index) => {
      const ids = [];
      item.forEach(item1 => {
        ids.push(item1.id);
      });
      const idsString = ids.join(',');
      this.idsArr.push(idsString);
      const valueItem = valueArr[index];
      console.log('valueItem', valueItem);
      validateForm.addControl('[' + idsString + '][price_discount]', this.fb.control(valueItem ? valueItem.price_discount : '', [Validators.required]));
      validateForm.addControl('[' + idsString + '][price_origin]', this.fb.control(valueItem ? valueItem.price_origin : '', [Validators.required]));
      validateForm.addControl('[' + idsString + '][in_stock]', this.fb.control(valueItem ? valueItem.in_stock : '', [Validators.required]));
      validateForm.addControl('[' + idsString + '][isbn]', this.fb.control(valueItem ? valueItem.isbn : ''));

    });

  }

  getarrAll(arr, returnArr, index, arr1) {
    for (let i = 0, len = arr[index].length; i < len; i++) {
      let index1 = index;
      const item = arr[index][i];
      const arr2 = arr1.slice();
      arr2.push(item);
      if (index1 == arr.length - 1) {
        returnArr.push(arr2);
      } else {
        index1++; //继续递归
        this.getarrAll(arr, returnArr, index1, arr2);
      }
    }
  }

  getskuAll(arr, sku, index, arr1) {
    for (let i = 0, len = arr[index].length; i < len; i++) {
      let index1 = index;
      const item = arr[index][i];
      const arr2 = arr1.slice();
      arr2.push(item.id);
      if (index1 == arr.length - 1) {
        sku.push(arr2);
      } else {
        index1++; //继续递归
        this.getskuAll(arr, sku, index1, arr2);
      }
    }
  }

  getInt(value) {
    return parseInt(value);
  }

  getarrindex(index, valueindex) {
    const arr = this.specArr1;
    if (arr.length == valueindex + 1) {
      return index % arr[valueindex];
    } else {
      const len = this.checkarr1(valueindex);
      const len1 = this.checkarr(valueindex);
      const bs = parseInt('' + index / len);
      return parseInt('' + (index - bs * len) / len1);
    }
  }

  checkarr1(index) {
    let total = 1;
    const arr = this.specArr1;
    for (let i = index, len = arr.length; i < len; i++) {
      total = total * (arr[i] || 1);
    }
    return total;
  }

  checkarr(index) {
    let total = 1;
    const arr = this.specArr1;
    for (let i = index, len = arr.length; i < len; i++) {
      total = total * (arr[i + 1] || 1);
    }
    return total;
  }

  gcd(a, b) {
    let minNum = Math.min(a, b), maxNum = Math.max(a, b), i = 1, vper = 0;
    if (a === 0 || b === 0) {
      return maxNum;
    }

    for (; i <= minNum; i++) {
      vper = maxNum * i;
      if (vper % minNum === 0) {
        break;
      }
    }
    return vper;
  }

  gcds(arr) {
    let onum = 0, i = 0, len = arr.length, midNum = 0;
    for (; i < len; i++) {
      onum = Math.floor(arr[i]); //去掉小数
      midNum = this.gcd(midNum, onum);
    }
    return midNum;
  }

  delObj = {};

  deletSpecItem(item, index, item1) {
    console.log('ffffff:', item[index].attribute_value_id1, item1);
    if (item[index].attribute_value_id1) {
      this.delObj[item1.attribute_id] = 1;
    }
    item.splice(index, 1);
  }

  addspec1(item) { //添加规格值
    const len = item.childLen;
    this.validateForm.addControl('spec[' + item.index + '][' + len + ']', this.fb.control(''));
    item.childLen++;
    item.list.push({title: '', index: len});
  }

  down(index) {
    const specList = this.specList;
    const len = specList.length;
    if (index < len - 1) {
      const nowitem = specList[index];
      specList[index] = specList[index + 1];
      specList[index + 1] = nowitem;
      this.setspecArr();
      this.update_norm_mode = 1;
    }
  }

  up(index) {
    const specList = this.specList;
    if (index > 0) {
      const nowitem = specList[index];
      specList[index] = specList[index - 1];
      specList[index - 1] = nowitem;
      this.setspecArr();
      this.update_norm_mode = 1;
    }
  }

  remove(index, item) {//删除规格
    if (this.specList.length > 1) {
      const delItem = this.specList[index];
      this.specList.splice(index, 1);
      this.validateForm.removeControl('spec[' + item.index + ']');
      if (item.attribute_id1) {
        this.update_norm_mode = 1;
      }
      item.list.forEach(item1 => {
        this.validateForm.removeControl('spec[' + item.index + '][' + item1.index + ']');
      });
      //this.valueArr.splice(index)
      const valueArr = this.valueArr;

      const saveObj = {}; //值剩余
      this.valueArr = valueArr.filter(item => {
        item.sku_info.sku2.splice(index, 1); //sku value list 移除

        let ids = item.sku_info.sku2.map(item1 => {
          return item1.goods_attribute_value_id;
        });
        ids = ids.join('-');
        if (!saveObj[ids]) {
          saveObj[ids] = 1;
          return true;
        } else {
          return false;
        }
      });

      this.setspecArr(); //得到 规格table list
    }
  }

  addspec(e) { //添加规格
    e.preventDefault();
    const len = this.specIndex;
    this.validateForm.addControl('spec[' + len + ']', this.fb.control(''));
    this.validateForm.addControl('spec[' + len + '][0]', this.fb.control(''));
    this.specList.push({
      edit: true,
      title: '',
      index: len,
      childLen: 1,
      valuelen: 0,
      valueindex: 0,
      list: [
        {title: '', index: 0}
      ]
    });
    this.specIndex++;
  }

  addType() {
    if (this.typeValue) {
      this.addTypeValue();
    } else {
      this.addshow = false;
    }
  }

  cateChage(e) {
    console.log(e);
  }

  checkTag(item) {
    console.log('item', item);
    this.categories = item.id;
    item.checked = !item.checked;
    if (item.checked) {
      item.bind = true;
    } else {
      item.bind = false;
    }
  }

  addInput(e) {
    e.stopPropagation();
    this.addshow = true;
  }

  addTypeValue() {
    this.ProductlistService.postAddGroup({name: this.typeValue, sort: 0}).subscribe(res => {
      if (res.code == 2000) {
        this.typeValue = '';
        this.addshow = false;
        this.getGroupList();
        this._message.create('success', '分类添加成功');
      } else {
        this._message.create('error', res.message);
      }

    });
  }

  getGroupList(id = null) {// 获取分组
    this.ProductlistService.getGroupList(this.shopid).subscribe(res => {
      if (res.code === 200) {
        let data = res.data.list;
        data.forEach((item, index) => {
          if (item.son) {
            item.children = item.son;
          }
          return true;
        });
        console.log('groupList', data);
        this.groupList = data;
      }
    });
  }

  getTempList(id = null) {
    this.templateService.getTemplateList(this.shopid).subscribe(res => {
      this.templateList = res.data.data;
    });
    // this.ProductlistService.getGroupList().subscribe(res => {
    //   if (res.code == 2000) {
    //     this.groupList = res.data.data;
    //     if (id) {
    //       this.ProductService.getAppletGoodsCategoryRelationBindList(id).subscribe(res1 => {
    //         if (res1.code == 2000) {
    //           let data = res1.data;
    //           let arr = data.map(item => {
    //             return item.applet_goods_category_id;
    //           });
    //           this.groupList.forEach(item => {
    //             if (arr.indexOf(item.id) >= 0) {
    //               item.checked = true;
    //               item.bind = true;
    //             }
    //           })
    //         }
    //       })
    //     }
    //   }
    //   this._isSpinning = false;
    // })
  }
}
